package com.yugao.fintech.antelope.base.security.utils;

import cn.hutool.core.convert.Convert;
import com.yugao.fintech.antelope.base.model.constants.SecurityCons;
import com.yugao.fintech.antelope.base.model.module.auth.LoginUser;
import com.yugao.fintech.antelope.base.model.module.auth.LoginUserHolder;
import com.yugao.fintech.framework.assistant.utils.StringUtils;
import com.yugao.fintech.framework.assistant.utils.exception.BizException;
import com.yugao.fintech.framework.core.utils.ServletUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import javax.servlet.http.HttpServletRequest;

/**
 * 权限获取工具类
 */
@Slf4j
public class SecurityUtils {
    /**
     * 获取用户
     */
    public static String getUserName() {
        return ServletUtils.urlDecode(getLoginUser().getUserName());
    }

    /**
     * 获取用户ID
     */
    public static Long getUserId() {
        return Convert.toLong(getLoginUser().getUserId());
    }

    /**
     * 获取登录用户
     */
    public static LoginUser getLoginUser() {
        return LoginUserHolder.get();
    }

    /**
     * 获取请求token
     */
    public static String getToken() {
        return getToken(ServletUtils.getRequest().orElseThrow(() -> new BizException("request is null")));
    }

    /**
     * 根据request获取请求token
     */
    public static String getToken(HttpServletRequest request) {
        if (request == null) {
            return "";
        }
        String token = request.getHeader(HttpHeaders.AUTHORIZATION);
        if (token == null) {
            return "";
        }
        if (StringUtils.isNotEmpty(token) && token.startsWith(SecurityCons.ACCESS_TOKEN_PREFIX)) {
            token = token.replace(SecurityCons.ACCESS_TOKEN_PREFIX, "");
        }
        return token;
    }

    /**
     * 是否为管理员
     *
     * @param userId 用户ID
     * @return 结果
     */
    public static boolean isAdmin(Long userId) {
        return userId != null && 1L == userId;
    }

    /**
     * 生成BCryptPasswordEncoder密码
     *
     * @param password 密码
     * @return 加密字符串
     */
    public static String encryptPassword(String password) {
        if (StringUtils.isEmpty(password)) {
            return "";
        }
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.encode(password);
    }

    /**
     * 判断密码是否相同
     *
     * @param rawPassword     真实密码
     * @param encodedPassword 加密后字符
     * @return 结果
     */
    public static boolean matchesPassword(String rawPassword, String encodedPassword) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.matches(rawPassword, encodedPassword);
    }

//    /**
//     * 获取用户角色信息
//     * @return 角色集合
//     */
//    public List<Long> getRoles() {
//        Collection<GrantedAuthority> authorities = LoginContextHolder.get().getAuthenticatedUser().getAuthorities();
//        List<Long> roleIds = new ArrayList<>();
//        authorities.stream().filter(granted -> StrUtil.startWith(granted.getAuthority(), SecurityCons.ROLE))
//                .forEach(granted -> {
//                    String id = StrUtil.removePrefix(granted.getAuthority(), SecurityCons.ROLE);
//                    roleIds.add(Long.parseLong(id));
//                });
//        return roleIds;
//    }

    /**
     * 判断是否来自内部请求
     */
    public static boolean isFromInner() {
        HttpServletRequest request = ServletUtils.getRequest().orElseThrow(() -> new RuntimeException("request is null"));
        String source = request.getHeader(SecurityCons.FROM_SOURCE);
        // 内部请求验证
        return StringUtils.equals(SecurityCons.FROM_IN, source);
    }
}
